package warmachineroster.service.validation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import warmachinesystem.BaseUnit;

public class UnitCounter {

	private Map<BaseUnit, Integer> unitCount = new HashMap<BaseUnit, Integer>();

	public void incrementUnitCount(BaseUnit bu) {
		Integer count = unitCount.get(bu);
		if (count == null) {
			count = 1;
		} else {
			count++;
		}
		unitCount.put(bu, count);
	}
	
	public void decrementUnitCount(BaseUnit bu) {
		Integer count = unitCount.get(bu);
		if (count == null || count == 0) {
			throw new IllegalStateException(
					"si è cercato di decrementare il conteggio di un'unità inesistente");
		} else {
			count--;
		}
		unitCount.put(bu, count);
	}
	
	public Map<BaseUnit, Integer> getCount(){
		return new HashMap<BaseUnit, Integer>(unitCount);
	}
	
	public List<BaseUnit> getUnits(){
		List<BaseUnit> result = new ArrayList<BaseUnit>();
		for (Map.Entry<BaseUnit, Integer> entry : unitCount.entrySet()){
			if (entry.getValue() > 0)
				result.add(entry.getKey());
		}
		return result;
	}

	public Integer getCount(BaseUnit referenceUnit) {
		return unitCount.get(referenceUnit) == null ? 0: unitCount.get(referenceUnit);
	}
	
}
